"""
Views that return JSON pages.
"""

from django.contrib.auth.decorators import login_required
from django.utils import simplejson as json
from django.http import HttpResponse

from django.db.models import Q

from live.models import Tag
from live.models import VehicleTag
from live.models import UserProfile

@login_required
def tags(request):
  """Return list of tags"""
  response = HttpResponse(mimetype='application/json')
  
  try:
    tagSet = Tag.objects.filter(Q(user=request.user) | Q(is_public=True))
  except Tag.DoesNotExist, e:
    tagSet = []
  
  tags = dict(
    (tag.id, {
    'name':      tag.name,
    'slug':      tag.slug,
    'is_mine':   tag.user == request.user,
    'is_public': tag.is_public
      }) for tag in tagSet)
  
  response.write(json.dumps(tags))
  
  return response

@login_required
def vehicleTags(request):
  """Return list of (vehicle, tag) couples"""
  response = HttpResponse(mimetype='application/json')
  
  try:
    vehicleTagSet = VehicleTag.objects.filter(Q(tag__user=request.user) | Q(tag__is_public=True))
  except VehicleTag.DoesNotExist, e:
    vehicleTagSet = []
  
  vehicleTags = dict(
    (vehicleTag.id, (vehicleTag.vehicle.id, vehicleTag.tag.id))
      for vehicleTag in vehicleTagSet)
  
  response.write(json.dumps(vehicleTags))
  
  return response

@login_required
def saveOptions(request):
  """Stores a string to request.user.profile.options"""
  profile, created = UserProfile.objects.get_or_create(user=request.user)
  
  try:
    profile.options = request.POST['options']
    
    save = True
  except Exception, e:
    save = False
  
  if save:
    profile.save()
  
  return HttpResponse()

@login_required
def loadOptions(request):
  """Obtains the saved options for the current user"""
  response = HttpResponse(mimetype='application/json')
  
  profile, created = UserProfile.objects.get_or_create(user=request.user)
  
  response.write(json.dumps(profile.options))
  
  return response
  